<%@page import="net.groupme.gui.rendering.constants.RENDERING_CONSTANTS"%>
<%@page import="net.groupme.search.SEARCH_CONFIGURATION"%>
<%@page import="net.groupme.model.Group"%>
<%@page import="net.groupme.model.Resource"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.Map"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.lang.Integer"%>
<%@page import="net.groupme.model.Tag"%>
<%@page import="net.groupme.user.UserManager"%>
<%@page import="net.groupme.model.User"%>
<%@page import="net.groupme.model.ObjectFactory"%>
<%@page import="java.util.ListIterator"%>
<%@page import="java.util.Collection"%>
<%@page import="java.util.HashMap"%>
<%@page import="net.groupme.model.MODEL_CONSTANTS"%>
<%@page import="net.groupme.gui.constants.VIEW_VOCABULARY"%>
<%@page import="org.apache.commons.lang.StringEscapeUtils"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>

<div id="searchHead">
	
	<div id="searchForm">
		<form action="<%= VIEW_VOCABULARY.GROUPME_BASE_URL + VIEW_VOCABULARY.ACTION_SEARCH %>">
			<small>Enter tags:</small> <input id="searchInput" type="text" name="<%= VIEW_VOCABULARY.PARAMETER_KEYWORD %>" value="<c:out value='${keyword}'></c:out>"/> 
			<input style="font-size:0.8em;" type="submit" value="search"/>
			<br />
			<span>
				<input type="radio" name="<%= VIEW_VOCABULARY.PARAMETER_SEARCH_FOR %>" value="<%= VIEW_VOCABULARY.SEARCH_FOR_RESOURCES %>"/> <small>resources</small>
				<input type="radio" name="<%= VIEW_VOCABULARY.PARAMETER_SEARCH_FOR %>" value="<%= VIEW_VOCABULARY.SEARCH_FOR_GROUPS %>"/> <small>groups</small>
				<input type="radio" checked="checked" name="<%= VIEW_VOCABULARY.PARAMETER_SEARCH_FOR %>" value="<%= VIEW_VOCABULARY.SEARCH_FOR_GROUPS_AND_RESOURCES %>"/> <small>both</small>

				<input type="hidden"  name="<%= VIEW_VOCABULARY.PARAMETER_FREE_SEARCH %>" value="true"/>
				<input type="hidden"  name="<%= VIEW_VOCABULARY.PARAMETER_SEARCH_FOR_ALL %>" value="false"/>
				</span>
		</form>								
	</div>
</div>
								
<hr />
	
	<!-- searchresult div start -->
<div id="searchresult">
	<c:if test="${searchResultList != null}">
		<!-- search header -->
		<span style="font-size:small;"><b>Search Results for </b><i><c:out value="${keyword}"/></i></span>
		<p style="margin-bottom:10pt;">
			<small>
				Number of results: <c:out value="${searchManager.actualNumberOfResults}"/><br/>
			</small>
		</p>
		
		<c:set var="resultList" value="${searchResultList}"></c:set>
		<c:set var="filter" value="${filter}"></c:set>
		<c:set var="filteredSearchResultList" value="${filteredSearchResultList}"></c:set>
		<c:set var="numberofResults" value="${searchManager.actualNumberOfResults}"></c:set>
			
		<!-- searchresultlist div start -->
		<div id="searchresultList">
		<%!
	    private String getStringValue(HttpServletRequest request, String parameter){
	    	String value = request.getParameter(parameter);
	    	if(value == null && request.getAttribute(parameter) != null){ //normally this is not accessed but we do our best to extract the value.. 
	    		value = request.getAttribute(parameter).toString();
	    	}
	    	return value;
	    }
		
		%>
		
		<% 	
			
			double numberofSearchResults = 0.0;
			
			//the search result list is split into result pages, each containing max. 10 seach result resources
			int numberofResultPages = 1;
			
			//the hole result list
			List<Resource> resultlist = (List<Resource>) pageContext.getAttribute("resultList");
			int resultListsize = Integer.parseInt(pageContext.getAttribute("numberofResults").toString());
			
			//the filtered result list
			List<Resource> filteredList = (List<Resource>) pageContext.getAttribute("filteredSearchResultList");
			
			//setting the list to be displayed
			List<Resource> displayedList = new ArrayList<Resource>();
			
			String filter = request.getParameter("filter");
			
			if(pageContext.getAttribute("filter") != null){
				displayedList = filteredList;
				numberofSearchResults = filteredList.size();
			}else {
				displayedList = resultlist;
				numberofSearchResults = Double.parseDouble(pageContext.getAttribute("numberofResults").toString());
			}
			
			int currentPage = 0;
			if(request.getParameter("pageID") != null){
				currentPage = Integer.parseInt(request.getParameter("pageID"));
			}else {
				currentPage = 1;
			}
			
			//start and end of the list-iterator
			int iterStart = (currentPage * 10) - 10;
			int iterEnd = iterStart + 9;

			//mapping of resource type to integer values 
			Map<String, Integer> resourceTypes = new HashMap<String, Integer>();
			resourceTypes.put(MODEL_CONSTANTS.RESOURCE_TYPE_GROUP, 1);
			resourceTypes.put(MODEL_CONSTANTS.RESOURCE_TYPE_IMAGE, 2);
			resourceTypes.put(MODEL_CONSTANTS.RESOURCE_TYPE_AUDIO, 3);
			resourceTypes.put(MODEL_CONSTANTS.RESOURCE_TYPE_VIDEO, 4);
			resourceTypes.put(MODEL_CONSTANTS.RESOURCE_TYPE_WEBSITE, 5);
			resourceTypes.put(MODEL_CONSTANTS.RESOURCE_TYPE_RSS, 6);
			resourceTypes.put(MODEL_CONSTANTS.RESOURCE_TYPE_SHOCKWAVE, 7);
			resourceTypes.put(MODEL_CONSTANTS.RESOURCE_TYPE_MULTIMEDIA, 8);
			
			//counting resource types
			int numberofImages = 0;
			int numberofGroups = 0;
			int numberofAudios = 0;
			int numberofVideos = 0;
			int numberofWebsites = 0;
			int numberofRSS = 0;
			int numberofFlash = 0;
			int numberofMultimedia = 0;
			
			Iterator<Resource> countIter = resultlist.iterator();
			
			while (countIter.hasNext()){
				Resource res = countIter.next();
				
				int r_Type = resourceTypes.get(res.getType());
				switch(r_Type){
				
					case 1:
						//numberofGroups = numberofGroups + 1;
						numberofGroups++;
						break;
					case 2:
						//numberofImages = numberofImages + 1;
						numberofImages++;
						break;
					case 3:
						//numberofAudios = numberofAudios + 1;
						numberofAudios++;
						numberofMultimedia++;
						break;
					case 4:
						//numberofVideos = numberofVideos + 1;
						numberofVideos++;
						numberofMultimedia++;
						break;
					case 5:
						//numberofWebsites = numberofWebsites + 1;
						numberofWebsites++;
						break;
					case 6:
						//numberofRSS = numberofRSS + 1;
						numberofRSS++;
						break;
					case 7:
						//numberofFlash = numberofFlash + 1;
						numberofFlash++;
						numberofMultimedia++;
						break;
				}
			}

			//creating links for resource types that should be filtered from the result lsit
			String keyword = getStringValue(request, VIEW_VOCABULARY.PARAMETER_KEYWORD);
			keyword = keyword.replace("\"", "");
			String freeSearch = getStringValue(request, VIEW_VOCABULARY.PARAMETER_FREE_SEARCH);
			String searchfor = getStringValue(request, VIEW_VOCABULARY.PARAMETER_SEARCH_FOR);
			String andsearch = getStringValue(request, VIEW_VOCABULARY.PARAMETER_SEARCH_FOR_ALL);

			String searchRequestURL = "";
			
			if(keyword.contains(" ")){
				//searchRequestURL = request.getContextPath() + "/" + VIEW_VOCABULARY.ACTION_SEARCH + "?" + VIEW_VOCABULARY.PARAMETER_KEYWORD + "=%22" + keyword + "%22" + "&searchfor=" + searchfor + "&freesearch=" + freeSearch + "&andsearch=" + andsearch;
				searchRequestURL = request.getContextPath() + "/" + VIEW_VOCABULARY.ACTION_SEARCH + "?" + VIEW_VOCABULARY.PARAMETER_KEYWORD + "=" + keyword + "&searchfor=" + searchfor + "&freesearch=" + freeSearch + "&andsearch=" + andsearch;
			}else{
				searchRequestURL = request.getContextPath() + "/" + VIEW_VOCABULARY.ACTION_SEARCH + "?" + VIEW_VOCABULARY.PARAMETER_KEYWORD + "=" + keyword + "&searchfor=" + searchfor + "&freesearch=" + freeSearch + "&andsearch=" + andsearch;
			}
			
			if(!VIEW_VOCABULARY.SEARCH_FOR_GROUPS.equals(searchfor)){
			%>
			
			<p style="margin-bottom:10pt;">
				<span style="float:left:"><strong>Show: </strong></span>
				<span>&nbsp;&nbsp;
					<a href="<%=searchRequestURL%>">
						all (<%= resultListsize %>)
					</a>&nbsp;&nbsp;
					<%if(numberofGroups != 0) {%>
					<a href="<%=searchRequestURL + "&" + VIEW_VOCABULARY.PARAMETER_FILTER_RESOURCETYPE + "=" + MODEL_CONSTANTS.RESOURCE_TYPE_GROUP%>">
						<img src="<%= request.getContextPath() +  "/images/g-16x16.gif"%>" style="border: 0pt none;"/> groups(<%=numberofGroups %>)
					</a>&nbsp;&nbsp;
					<%} 
					
					if(numberofImages != 0){%>
						
					<a href="<%=searchRequestURL + "&" +  VIEW_VOCABULARY.PARAMETER_FILTER_RESOURCETYPE + "=" + MODEL_CONSTANTS.RESOURCE_TYPE_IMAGE%>">
						<img src="<%= request.getContextPath() +  "/images/photo.png"%>" style="border: 0pt none;"/> images(<%=numberofImages %>)
					</a>&nbsp;&nbsp;
					<%}
					
					if(numberofMultimedia != 0){%>
						<a href="<%=searchRequestURL + "&" +  VIEW_VOCABULARY.PARAMETER_FILTER_RESOURCETYPE + "=" + MODEL_CONSTANTS.RESOURCE_TYPE_MULTIMEDIA%>">
							<img src="<%= request.getContextPath() +  "/images/multimedia2.png"%>" style="border: 0pt none;" width="16px"/> audio/video (<%=numberofMultimedia %>)
						</a>&nbsp;&nbsp;
					<%}
					
					if(numberofWebsites!= 0){%>
					<a href="<%=searchRequestURL + "&" +  VIEW_VOCABULARY.PARAMETER_FILTER_RESOURCETYPE + "=" + MODEL_CONSTANTS.RESOURCE_TYPE_WEBSITE%>">
						<img src="<%= request.getContextPath() +  "/images/page_world.png"%>" style="border: 0pt none;"/> website(<%=numberofWebsites %>)
					</a>&nbsp;&nbsp;
					<%}
					
					if(numberofRSS != 0){%>
					<a href="<%=searchRequestURL + "&" +  VIEW_VOCABULARY.PARAMETER_FILTER_RESOURCETYPE + "=" + MODEL_CONSTANTS.RESOURCE_TYPE_RSS%>">
						<img src="<%= request.getContextPath() +  "/images/rss.png"%>" style="border: 0pt none;"/> RSS(<%=numberofRSS %>)
					</a>&nbsp;&nbsp;
					<%}%>
				</span>
				<h4 id="resultTypeHeader">
				<% if(request.getParameter("filter") == null){
					out.print("Result type: all");
					} else {
						out.print("Result type: " + request.getParameter("filter"));
					} %>
				</h4>
			</p>
			<%
			}
			
			//create output for the result list
			if(numberofSearchResults > 10){
				numberofResultPages = (int) Math.ceil(numberofSearchResults / 10.0);
				
			}
	
			int count = iterStart;
			
				%>
				<!-- resultpage div start -->
				<div class="resultPage">
				
					<ol  start="<%=count + 1%>" id="resultpageList">
					<%

				ListIterator<Resource> it = displayedList.listIterator(iterStart);
					while(it.hasNext() &&  iterStart <= iterEnd){
								  
						
						iterStart = iterStart + 1;
						Resource actualResource = it.next();
						String requestType = VIEW_VOCABULARY.REQUEST_TYPE_RESOURCE;
			    		String imageAltAttribute = "";
			    		int imageWidth = 16;
			    		int imageHeight = 16;
								   
						//checking type of resource and setting output correspondig to the type
								   
						int ressourceType = resourceTypes.get(actualResource.getType());
						String thumbnail = null;
						String videoThumbnail = null;
						String videoURL = null;
						String videoForeground = request.getContextPath() + "/images/video_fg.png";
						String defaultgroupThumbnail = request.getContextPath() + "/images/groupimg-default.gif";
						String groupImageError = request.getContextPath() + "/images/groupErrorImg.png";
						String groupBorder = request.getContextPath() + "/images/group_bg.png";
						String groupBackground = request.getContextPath() + "/images/group.png";
						String brokenImage = request.getContextPath() + "/images/broken_img.png";
						boolean isGroup = false;
						boolean isImage = false;
						boolean isVideo = false;
						
						switch(ressourceType){
								   		
							case 1: //resource is a group
								String groupId = actualResource.getId();
								Group groupItem = ObjectFactory.getGroup(groupId);
								isGroup = true;
								
								Iterator<User> userIter = groupItem.getUsers("owner").iterator();
								User groupOwner = null;
								if (userIter.hasNext()){
									groupOwner = userIter.next();
								}
								
								try{
								
					    		thumbnail = groupItem.getActualGroupVisualization(groupOwner.getId()).getThumbnail();
								}
								catch(Exception e){
									
								}
								
					    		if (thumbnail== null){
									thumbnail = groupItem.getURLOfAPictureInGroup();
								}
										
								if (thumbnail== null & groupItem.getURLOfAPictureInGroup()==null){
									thumbnail = defaultgroupThumbnail;
								}
								requestType = VIEW_VOCABULARY.REQUEST_TYPE_GROUP;
								imageHeight = 65;
								imageWidth = 105;
								imageAltAttribute = "Group";
								
								break;
									   
							case 2: //resource is an image
								thumbnail = actualResource.getURL().toString();
								isImage = true;
								imageAltAttribute = "Image";
								imageHeight = 65;
								imageWidth = 105;
								break;
							case 3://resource is an audio file
								thumbnail = request.getContextPath() + "/images/audio.png";
								
								imageAltAttribute = "Audio";
								break;
							case 4: //resource is a video file
								videoURL = actualResource.getURL().toString();
								isVideo = true;
								//thumbnail = request.getContextPath() + "/images/video16x16.png";
								thumbnail = videoURL.substring(videoURL.lastIndexOf("/") + 1);
								imageHeight = 65;
								imageWidth = 105;
								imageAltAttribute = "Video";
								break;
							case 5: //resource is a website
								thumbnail = request.getContextPath() + "/images/page_world.png";
								imageAltAttribute = "Website";
								break;
							case 6: //resource is a rss feed
								thumbnail = request.getContextPath() + "/images/rss.png";
								imageAltAttribute = "RSS Feed";
								break;
							case 7: //resource is a shockwave file
								videoURL = actualResource.getURL().toString();
								isVideo = true;
								thumbnail = videoURL.substring(videoURL.lastIndexOf("/") + 1);
								thumbnail = "http://img.youtube.com/vi/" + thumbnail + "/2.jpg";
								imageHeight = 65;
								imageWidth = 105;
								//thumbnail = request.getContextPath() + "/images/flash16x16.png";
								imageAltAttribute = "Shockwave";
								break;
						}
						
						//generate result-item output
						
						%>
						<!-- list item  start -->
						<li>
						  <div class="resultListItem" <% if(isGroup){out.print("style=\"min-height:80px; background-image:url(" + groupBackground + "); background-repeat:repeat-x;\"");} %>>
						  	<div style="float:left; margin-right:1em; <% if (isGroup){out.print("background-image:url(" + groupBorder + "); background-repeat:no-repeat; height:80px; width:120px;");} else if(isVideo){out.print("background-image:url(" + thumbnail + "); background-repeat:no-repeat; height:65px; width:105px;");} %>">
					   			<!-- DELETE THIS: requestType + "/" + actualResource.getId() -->
					   			<a href="<%= actualResource.getURI()%>">
					   				<img src="<%if(isVideo){out.print(videoForeground); } else {out.print(thumbnail);}%>" width="<%=imageWidth %>" height="<%=imageHeight %>" alt="<%=imageAltAttribute %>" title="<%=actualResource.getType() %>" <%if(isGroup) {%> onerror="this.src='<%=groupImageError %>';"<%} else if (isImage){%> onerror="this.src='<%=brokenImage %>';"<%}%>/>
					   			</a>
					   		</div>
								<strong>
									<a href="<%= actualResource.getURI()%>">
										<% if(actualResource.getName().length() == 0 || actualResource.getName() == null){
											out.print("No Name (" + actualResource.getType() + ")");
										}else {
											out.print(StringEscapeUtils.escapeHtml(actualResource.getName()));
										}
										%>
									</a>
								</strong>
								<p> 
								<span style="font-size:0.8em; color:black">
								<% 
								
								if(actualResource.getDescription() != null){
									
									if(actualResource.getDescription().length() != 0){
										if(actualResource.getDescription().length() > 80){
											out.print(StringEscapeUtils.escapeHtml(actualResource.getDescription().substring(0, 80)));
											out.print(" ... " + "<a href=" + requestType + "/" + actualResource.getId() + "> more </a>" + " ...");
										}
										else 
											out.print(StringEscapeUtils.escapeHtml(actualResource.getDescription()));
										}
									else out.print("No description");
									
								}else {
									out.print("No description");
								}
								%>
								</span>
								</p>
						<%
			
			
						Collection<Tag> resourceTags = actualResource.getTags();
						Iterator<Tag> tagIterator = resourceTags.iterator();
						
					    if(tagIterator.hasNext()) {
							%>
							<small><strong>Tags:</strong>
							
							<%
						   
						   while(tagIterator.hasNext()){
							   Tag currentTag =  tagIterator.next();
							   String tagKeyword=  StringEscapeUtils.escapeHtml(currentTag.getKeyword());
							   %>
							   <a href="<%= currentTag.getURI()%>" title="Search for Groups and Resources related with <%=tagKeyword %>"><%= deleteRedundantCommas(tagKeyword) %></a><% if(tagIterator.hasNext()){ out.print(" - ");} %>
								   <%
						   }
							%>
							</small>
							<%
					    }else { 
					    	%>
					    	<small><strong>Tags:</strong> No tags</small>
					    	<%}%>
						   	</div>
						 
						 <br style="clear:left"/>
						</li>
					<!-- list item  end -->
					<%} %>																	   
					</ol>
				</div>

<div id="pagenumbers" style="text-align: center; margin-top: 1em;">
	<%
		
		String searchString = searchRequestURL;
		if(filter != null){
			searchString = searchString + "&" + VIEW_VOCABULARY.PARAMETER_FILTER_RESOURCETYPE + "=" + filter;
		}
		int resultListSize = (int) numberofSearchResults;
		if(resultListSize > 10){
			int numberofResultpages = (int) Math.ceil(resultListSize / 10.0);
			if(currentPage > 1){
				int showPrev = currentPage-1;
				%>
				<span><strong><a href="<%= searchString + "&" + VIEW_VOCABULARY.PARAMETER_FILTER_RESOURCETYPE + "=" + filter + "&pageID=" + showPrev %>">previous</a></strong></span>&nbsp;&nbsp;
				<%
			}
			out.print("<span>");
			if(numberofResultpages <= 10){
				for(int i = 1; i <= numberofResultpages; i++){
					%>
					<a href="<%= searchString + "&pageID=" + i %>" <%if(i == currentPage){out.print("style=\"font-weight:bold;color:red;\"");}%>><%=i %></a>
					<%
				}
			}else {
				if(numberofResultpages - currentPage >= 10){
					int start = 0;
					int end = 0;
					
					if(currentPage < 7){
						start = 1;
						end = 7;
					}else {
						
						%>
						<a href="<%= searchString + "&pageID=" + 1 %>"><%=1 %></a>
						<%
						out.print("&nbsp;...&nbsp;");
						start = currentPage - 3;
						end = currentPage + 3;
					}
					
					for(int i = start; i <= end; i++){
						%>
						<a href="<%= searchString +  "&pageID=" + i %>" <%if(i == currentPage){out.print("style=\"font-weight:bold;color:red;\"");}%>><%=i %></a>
						<%
					}
					out.print("&nbsp;...&nbsp;");
					%>
					<a href="<%= searchString +  "&pageID=" + numberofResultpages %>"><%=numberofResultpages %></a>
					<%
				}
				else {
					%>
					<a href="<%= searchString +  "&pageID=" + 1 %>"><%=1 %></a>
					<%
					out.print("&nbsp;...&nbsp;");
					//out.print("...&nbsp;");
					for(int i = numberofResultpages - 10; i <= numberofResultpages; i++){
						%>
						<a href="<%= searchString +  "&pageID=" + i %>" <%if(i == currentPage){out.print("style=\"font-weight:bold;color:red;\"");}%>><%=i %></a>
						<%
					}
				}
			}
			out.print("</span>");
			if(currentPage < numberofResultpages){
				int showNext = currentPage+1;
				%>
				<span><strong><a href="<%= searchString  + "&pageID=" + showNext %>">next</a></strong></span>&nbsp;&nbsp;
				<%
			}
		}
	%>
</div>																		
		</div>
	</c:if>											
</div>